package com.situ.mall.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.common.entity.Cart;
import com.situ.mall.common.mapper.CartMapper;
import com.situ.mall.common.mapper.ProductMapper;
import com.situ.mall.common.service.ICartService;
import com.situ.mall.common.util.RequestUtil;
import com.situ.mall.common.vo.CartVO;
import com.situ.mall.common.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author JavaWizard
 * @since 2023-09-19
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Autowired
    private ProductMapper productMapper;

    //添加商品到购物车
    @Override
    public ResultVO saveProduct(Integer pId) {
        ResultVO vo = new ResultVO();
        //从session中取出用户id，强制类型转换到int
        int memberId = (int)RequestUtil.getSession().getAttribute("currentId");
        //根据用户id 和 商品id，查购物车
        Cart c = baseMapper.selectBy2Id(memberId,pId);

        if (c == null){//没查着，添加商品
            Cart newCart = new Cart();
            newCart.setProductId(pId);//获取商品id
            newCart.setAmount(1);//获取添加数量
            newCart.setCreateTime(LocalDateTime.now());//获取添加时间
            newCart.setMemberId(memberId);//获取用户id
            baseMapper.insertCart(newCart);

            vo.setCode(0);
            vo.setMsg("商品添加成功");

        }else {//查着了，更新商品数量
            baseMapper.updateCart(c.getId(), c.getAmount()+1);

            vo.setCode(-1);
            vo.setMsg("商品数量+1");
        }
        return vo;
    }

    //查该会员购物车中的所有商品
    @Override
    public List<CartVO> selectAll(Integer memberId) {
        return baseMapper.selectAll(memberId);
    }

    //查购物车ids
    @Override
    public String selectByIds(String ids, Integer memberId) {
        String[] split = ids.split(",");
        //根据拆出来的商品id 和 用户id，去商品表里查
        List<String> list = baseMapper.selectByIds(split, memberId);
        StringBuilder s = new StringBuilder();
        int flag = 0;
        for (String string : list) {
            if (flag == 1){
                s.append(",");
            }
            s.append(string);
            flag = 1;
        }
        System.out.println(s.toString());
        return s.toString();
    }

    //购物车内删除商品
    @Override
    public void delete(Integer productId, Integer memberId) {
        baseMapper.deleteThis(productId, memberId);
    }
}
